#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from .api_security import APISecurity
from .error_code import error_code


class AppSecurity(object):
    """
    功能：单件模式app安全类
    """

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(AppSecurity, "_instance"):  # 反射
            AppSecurity._instance = object.__new__(cls)
        return AppSecurity._instance

    def public_verify(self):
        """公共参数校验"""

        def wrapper(func):
            def sub_wrapper(*args, **kwargs):
                # 公共校验，验证合法终端。get请求取问号后的参数，非get请求取body
                params = request.json if request.json else request.args
                public_auth = APISecurity().verify_public(params)
                if public_auth['code'] != 'SUCCESS':
                    return jsonify({'code': 10000, 'msg': error_code[10000]})
                return func(*args, **kwargs)

            return sub_wrapper

        return wrapper

    def token_verify(self):
        """token校验"""

        def wrapper(func):
            def sub_wrapper(*args, **kwargs):
                payload = APISecurity().verify_access_token()
                if not payload:
                    return jsonify({'code': 901, 'msg': error_code[901]})
                return func(*args, **kwargs)

            return sub_wrapper

        return wrapper
